<template>
  <div class="login-container">
    <el-form
      :rules="rules"
      ref="form"
      :model="form"
      label-width="80px"
      class="login-form"
    >
      <h2 class="login-title">登录</h2>
      <el-form-item label="帐号" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"> </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('form')">登录</el-button>
        <a href="/register">注册</a>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login, getUserInfo } from "@/api/user";
export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      rules: {
        username: [{ required: true, message: "请输入账号", triger: "blur" }],
        password: [{ required: true, message: "请输入密码", triger: "blur" }],
      },
    };
  },
  components: {},
  methods: {
    // 注意：按钮上调用的函数名要一致 submitForm
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.form.username, this.form.password).then((response) => {
            const resp = response.data;
            // console.log(resp);
            if (resp.flag) {
              getUserInfo(resp.data.token).then((response) => {
                const respUser = response.data;

                if (respUser.flag) {
                  //true

                  // 将信息保存到浏览器的 localStorage 中
                  localStorage.setItem(
                    "b0352-sms-user",
                    JSON.stringify(respUser.data)
                  );
                  // 方便后面重新验证
                  localStorage.setItem("b0352-sms-token", resp.data.token);
                  // 前往首页
                  this.$router.push("/");
                } else {
                  // 获取信息失败, 弹出警告
                  this.$message({
                    message: respUser.message,
                    type: "warning",
                  });
                }
              });
            } else {
              // 获取信息失败, 弹出警告
              this.$message({
                message: resp.message,
                type: "warning",
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.login-form {
  width: 350px;
  /* 上下间隙150px, 左右自动 */
  margin: 160px auto;
  /*透明背景色*/
  background-color: rgb(255, 255, 255, 0.8);
  padding: 30px;
  /* 圆角 */
  border-radius: 20px;
}

.login-container {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url("../../assets/天空.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  overflow: hidden;
}

/* 标题 */
.login-title {
  text-align: center;
  color: #303133;
}
</style>
